package com.alex.seo.service.scheduler;

import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.transaction.annotation.Transactional;

import com.alex.seo.service.scheduler.dto.JobDTO;

@Transactional
public class SchedulerServiceBean implements SchedulerService {

	private static final Logger LOGGER = LoggerFactory.getLogger(SchedulerServiceBean.class);
	
	private Scheduler scheduler;
	
	@Required
	public void setScheduler(Scheduler scheduler) {
		this.scheduler = scheduler;
	}
	
	@Override
	public <JobParamType> void schedule(JobDTO<JobParamType> jobDTO) throws SchedulerServiceException {
		try {
			String jobGroup = jobDTO.getJob().getSimpleName();
			JobKey jobKey = new JobKey(jobDTO.getJobId(), jobGroup);
			
			JobDetail jobDetail = scheduler.getJobDetail(jobKey);
			if (jobDetail != null) {
				LOGGER.warn("Job ID={}, GROUP={} already exists and will be recreated.", jobDTO.getJobId(), jobGroup);
				scheduler.deleteJob(jobKey);
			}
			
			jobDetail = JobBuilder.newJob(GenericJob.class)
					.withIdentity(jobDTO.getJobId(), jobGroup)
					.build();
			
			jobDetail.getJobDataMap().put(JobConstants.JOB_CLASS, jobDTO.getJob());
			jobDetail.getJobDataMap().put(JobConstants.JOB_PARAM, jobDTO.getParam());
			jobDetail.getJobDataMap().put(JobConstants.JOB_SCHEDULER, jobDTO.getScheduler());
			
			SchedulerUtil.scheduleJob(scheduler, jobDTO.getScheduler(), jobDetail);
		} catch (SchedulerException e) {
			throw new SchedulerServiceException(e);
		}
	}
}
